//固件升级(bin)
var PageDownloadFW = {
    id: "PageDownloadFW", //页面id
    menu: "i18n.lan.menu.other", //所属菜单(一级菜单名)
    title: "i18n.lan.menu.PageDownloadFW", //标题（二级菜单名）
    icon: "icon-me-output", //图标
    init: function () {
        setTimeout(function () {
            eval("receivers").push(PageDownloadFW_dataReceived); //添加接收串口数据的函数
            eval("lineReceivers").push(PageDownloadFW_newLineReceived); //添加接收行数据的函数
        }, 3000);
    },
    el: [ //控件
        { //样式
            elname: "style",
            text: "#PageDownloadFW button,#PageDownloadFW label,#PageDownloadFW input[type=text]{margin-left:10px;padding-left:5px;padding-right:5px;}"
        },
        { //接收控件
            elname: "textarea",
            attrs: {
                style: "width:600px;height:420px;resize:none;outline:none;",
                id: "PageDownloadFW_recvTA",
                readonly: "readonly",
                //获得焦点不自动滚动
                onfocus: "PageDownloadFW_scroll = false",
                onblur: "PageDownloadFW_scroll = true"
            },
        },
        { //接收控件2
            elname: "textarea",
            attrs: {
                style: "width:240px;height:420px;margin-left:10px;resize:horizontal;",
                id: "PageDownloadFW_recvTA2",
                readonly: "readonly"
            },
        },
        { //清空
            elname: "button",
            text: i18n.lan.PageDownloadFW.clear,
            endRow: true,
            attrs: {
                onclick: "$('#PageDownloadFW_recvTA')[0].innerHTML='';$('#PageDownloadFW_recvTA2')[0].innerHTML=''",
                style: "margin-left:20px;position:relative;top:-10px"
            },
        },
        { //文件选择器
            elname: "text",
            attrs: {
                type: ("text"),
                value: "",
                id: "PageDownloadFW_file",
                disabled: true,
                style: "width: 500px;height: 30px;position:relative;bottom:1px;margin-right:20px;"
            },
        },
        { //选择升级文件
            elname: "button",
            text: i18n.lan.PageDownloadFW.chooseUpgradeFile,
            attrs: {
                onclick: "PageDownloadFW_chooseFile()",
            },
        },
        { //升级
            elname: "button",
            text: i18n.lan.PageDownloadFW.upgrade,
            attrs: {
                id: "PageDownloadFW_upgradeBtn",
                onclick: "PageDownloadFW_changeUpgrateState()",
                title: i18n.lan.PageDownloadFW.upgradeTitle
            },
            endRow: true,
        },
        {
            elname: "span",
            text: i18n.lan.PageDownloadFW.tip,
        }
    ],
}
CmdPage.add(PageDownloadFW); //添加到页面管理

var PageDownloadFW_upgradeState = false;
var PageDownloadFW_scroll = true;
var PageDownloadFW_upgradeStartTime = 0; //开始升级时间
var PageDownloadFW_lastSentTime = 0; //最后发送时间
var PageDownloadFW_filesize = 0; //文件大小
var PageDownloadFW_fileBytesSum = 0; //文件校验
var PageDownloadFW_upgradePartLen = 256; //升级文件分片大小
var PageDownloadFW_repeatCount = 0; //重复次数

//添加日志
function PageDownloadFW_appendLog(msg) {
    let ta = $('#PageDownloadFW_recvTA2');
    ta.autoScroll = true; //自动滚动
    ta.append(msg);
    scrollToTextareaEnd(ta[0], PageDownloadFW_scroll);
}
/**
 * 修改升级状态
 */
function PageDownloadFW_changeUpgrateState(state) {
    if ($('#PageDownloadFW_file').val()) { //没有选择文件不能切换状态
        if (typeof state == "undefined") { //未定义状态=>切换状态
            state = !PageDownloadFW_upgradeState;
        }
        PageDownloadFW_upgradeState = state;
        //显示颜色修改
        $('#PageDownloadFW_upgradeBtn').css("color", PageDownloadFW_upgradeState ? "red" : "black");
        cmdProgressChanged(0);
        PageDownloadFW_fileBytesSum = 0;
        GetFileDataSum($('#PageDownloadFW_file').val(), "PageDownloadFW_updateFileDataSum", "alert");
    } else {
        alert(i18n.lan.PageDownloadFW.chooseFile);
    }
}

/**
 * 更新sum
 * @param {返回的结果}} sum 
 */
function PageDownloadFW_updateFileDataSum(sum) {
    PageDownloadFW_fileBytesSum = parseInt(sum);
    PageDownloadFW_appendLog("sum={0}\n".format(sum));
}
//接收到串口数据
function PageDownloadFW_dataReceived(msg) {
    let ta = $("#PageDownloadFW_recvTA");
    if (defined(ta) && ta[0]) { //对象存在
        ta.append(msg);
        scrollToTextareaEnd(ta[0], PageDownloadFW_scroll);
    }
}
//接收到行数据
function PageDownloadFW_newLineReceived(line) {
    //PageDownloadFW_appendLog(line+"\n");
    if (line.startsWith("RTC Clock Init Failed!")) {
        alert("RTC Clock Init Failed!");
    } else if (line.startsWith("Spi Not Inited")) {
        alert(i18n.lan.PageDownloadFW.notSpiFlash);
    }
    if (PageDownloadFW_upgradeState) {
        $('#PageDownloadFW_recvTA').val();
        if (line.indexOf('Waiting Uart Command') != -1) {
            sendData("%%%%%%%%%%");
            PageDownloadFW_appendLog(i18n.lan.PageDownloadFW.readyToUpgrade + "\n");
        } else if (line.startsWith('Waiting Command FSPLOAD')) {
            PageDownloadFW_filesize = 0;
            PageDownloadFW_repeatCount = 0;
            sendCmd("FSPLOAD" + PageDownloadFW_fileBytesSum);
            PageDownloadFW_appendLog(i18n.lan.PageDownloadFW.sendUpgradeCmd + "\n");

        } else if (line.indexOf('$CONNECTED') == 0) {
            PageDownloadFW_appendLog(i18n.lan.PageDownloadFW.startSendFile + "\n");
            PageDownloadFW_upgradeStartTime = parseInt(new Date().getTime() / 1000);
            sendFile($('#PageDownloadFW_file').val(), PageDownloadFW_upgradePartLen, 0, "PageDownloadFW_SendFileResult", "alert");
        } else if (line.indexOf("+RECV ") == 0) {
            sendFile($('#PageDownloadFW_file').val(), PageDownloadFW_upgradePartLen, -1, "PageDownloadFW_SendFileResult", "alert"); //发送未完成的数据
        } else if (line.startsWith("File Finished")) {
            PageDownloadFW_lastSentTime = parseInt(new Date().getTime() / 1000);
            PageDownloadFW_appendLog((i18n.lan.PageDownloadFW.sendProgressTip + "\n").format(PageDownloadFW_filesize, PageDownloadFW_lastSentTime - PageDownloadFW_upgradeStartTime));
        } else if (line.startsWith("FW File CheckSum Is ")) {
            let regex = new RegExp("Is (\\d+)");
            //检查检验值
            if (regex.test(line)) {
                let sum = regex.exec(line)[1];
                let sumRight = PageDownloadFW_fileBytesSum == sum;
                PageDownloadFW_appendLog((i18n.lan.PageDownloadFW.validateTip + "\n").format((sumRight ? i18n.lan.PageDownloadFW.success : i18n.lan.PageDownloadFW.fail), PageDownloadFW_fileBytesSum, sum));
                PageDownloadFW_appendLog((i18n.lan.PageDownloadFW.repeatTimesTip + "\n").format(PageDownloadFW_repeatCount));
            }

        } else if (line.indexOf("+REPEAT") == 0) { //需要重复发送
            let index = parseInt(line.split(" ")[1]);
            PageDownloadFW_appendLog("x");
            PageDownloadFW_repeatCount += 1;
            sendFile($('#PageDownloadFW_file').val(), PageDownloadFW_upgradePartLen, index, "PageDownloadFW_SendFileResult", "alert"); //发送上一次数据
        } else if (line.startsWith("Just Goto")) {
            PageDownloadFW_changeUpgrateState(false);
            // alert(i18n.lan.PageDownloadFW.upgradeComplete);
        }
    }
}

//文件发送回复
function PageDownloadFW_SendFileResult(msg) {
    let msgs = JSON.parse(msg);
    //文件字节大小
    if (msgs.filesize) {
        PageDownloadFW_filesize = parseInt(msgs.filesize);
    }
    //文件所有字节的和
    // if (msgs.fileBytesSum) {
    //     PageDownloadFW_fileBytesSum = msgs.fileBytesSum;
    // }
    if (msgs.part && msgs.parts) {
        if (msgs.part == "1" && msgs.filesize) { //提示文件大小和分段
            PageDownloadFW_appendLog((i18n.lan.PageDownloadFW.filePartTip + "\n").format(msgs.filesize, PageDownloadFW_upgradePartLen, msgs.parts));
        }
        //发送完成
        if (msgs.part == msgs.parts) {
            PageDownloadFW_appendLog("\n" + i18n.lan.PageDownloadFW.fileSendComplete + "\n");
        } else {
            PageDownloadFW_appendLog("."); //可看作进度条
            cmdProgressChanged(parseInt(msgs.part) * 100 / parseInt(msgs.parts));
        }
    } else { //没有part数据
        if (msgs.tip) {
            //PageDownloadFW_appendLog(msgs.tip);
        } else {
            PageDownloadFW_appendLog(msgs);
        }
    }

}
/**
 * 选择文件回调
 * @param {*} fname 
 */
function PageDownloadFW_chooseFileOk(fname) {
    $("#PageDownloadFW_file").val(fname);
}
/**
 * 选择文件
 */
function PageDownloadFW_chooseFile() {
    ChooseFile("", "PageDownloadFW_chooseFileOk", "alert");
}
//临时添加按钮（读卡和信号）
//js:PageDownloadFW.el.push({elname: "button", text:"读卡",attrs:{onclick:"sendCmd('GSMATAT+QCCID')",title:i18n.lan.PageDownloadFW.readSimcardTitle}});PageDownloadFW.el.push({elname: "button", text:"信号",attrs:{onclick:"sendCmd('GSMATAT+CSQ')",title:i18n.lan.PageDownloadFW.readSimcardTitle}});